var express = require('express');
const stuinfor = express.Router();
var bodyParser = require('body-parser');
const path = require("path");
const Database = require("better-sqlite3");
//获取数据库中管理员账号密码等信息
const mydb = new Database(path.resolve(__dirname, "../database/infor.db"), { verbose: console.log });

// 创建 application/x-www-form-urlencoded 编码解析
stuinfor.use(bodyParser.urlencoded({ extended: false }))
stuinfor.use(express.json());
stuinfor.use(bodyParser.json());

// console.log("a1");
stuinfor.post('/stusearch', function (req, res) {
    // console.log("a2");
    // 输出 JSON 格式
    var response =  req.body.search_container;
    console.log(response);
    //指定数据库文件路径
    const get_user_by_id = mydb.prepare('SELECT stu_id,name,sex,birth,identification,tele_num,register,useful,borrow_num FROM student WHERE stu_id= ?');//一个查询语句对象
    var a = get_user_by_id.all(response);//执行查询
    // console.log(a);
    if (a) {
        // 查询成功,
        console.log('查询成功');
        // 把查询到的数据写入json文件中
        const { writeFile } = require('fs');
        var t = { "code": 0, "msg": "", "count": 100, "data": a };
        const jsonpath = path.resolve(__dirname, "../public/js/studata.json");
        const config = t;
        writeFile(jsonpath, JSON.stringify(config, null, 2), (error) => {
            if (error) {
                console.log('An error has occurred ', error);
                return;
            }
            console.log('Data written successfully to disk');
        });
        res.sendFile(path.resolve(__dirname, "../public/html/stu_search_result.html"));
    }
    else {
        console.log('没有此学生');
        // 查询失败,则返回查询界面
        res.sendFile(path.resolve(__dirname, "../public/html/search_error.html"));
    }
});

module.exports = stuinfor;